import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import api from '../../services/api.js';
import { mockDevices } from '../../mock/data';

// fetchDevices 异步 Thunk 函数
// 用于获取设备列表数据
export const fetchDevices = createAsyncThunk(
  'device/fetchDevices',
  async (params = {}, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));

      // 配置标志：设置为true时调用真实API，设置为false时使用模拟数据
      const USE_REAL_API = true; // 修改此标志来切换使用真实API或模拟数据
      
      if (false) {
        // 开发环境：使用模拟数据
        // 确保 mockDevices 是一个数组
        const devicesData = Array.isArray(mockDevices) ? [...mockDevices] : [];
        
        console.log('fetchDevices - 使用模拟数据:', {
          originalCount: devicesData.length,
          hasData: devicesData.length > 0,
          params: params
        });

        let filteredDevices = [...devicesData];

        // 关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase();
        filteredDevices = filteredDevices.filter(device => 
          (device.deviceName && device.deviceName.toLowerCase().includes(keyword)) || 
          (device.deviceCode && device.deviceCode.toLowerCase().includes(keyword))
        );
      }

      // 设备类型过滤
      if (params.deviceType && params.deviceType !== 'all') {
        filteredDevices = filteredDevices.filter(device => 
          device.deviceType === params.deviceType
        );
      }

      // 日期范围过滤
      if (params.startDate || params.endDate) {
        filteredDevices = filteredDevices.filter(device => {
          const deviceDate = new Date(device.createdAt);
            const startDate = params.startDate ? new Date(params.startDate) : new Date(0);
            const endDate = params.endDate ? new Date(params.endDate) : new Date();
            return deviceDate >= startDate && deviceDate <= endDate;
          });
        }

        // 分页
        const { page = 1, pageSize = 10 } = params;
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedDevices = filteredDevices.slice(startIndex, endIndex);

        const result = {
          devices: paginatedDevices,
          total: filteredDevices.length
        };
        
        console.log('fetchDevices - 返回结果:', {
          paginatedCount: paginatedDevices.length,
          totalCount: filteredDevices.length
        });
        
        return result;
      } else {
        // 调用实际的 API
        console.log('fetchDevices - 调用真实API:', {
          url: '/devices',
          params: {
            page: params.page || 1,
            pageSize: params.pageSize || 10,
            keyword: params.keyword,
            deviceType: params.deviceType,
            startDate: params.startDate,
            endDate: params.endDate
          }
        });
        const response = await api.get('/devices', {
          params: {
            page: params.page || 1,
            pageSize: params.pageSize || 10,
            keyword: params.keyword,
            deviceType: params.deviceType,
            startDate: params.startDate,
            endDate: params.endDate
          }
        });
        return response.data;
      }
    } catch (error) {
      console.error('fetchDevices - 错误:', error);
      return rejectWithValue(error.response?.data || '获取设备列表失败');
    }
  }
);

// createDevice 异步 Thunk 函数
// 用于创建新设备
export const createDevice = createAsyncThunk(
  'device/createDevice',
  async (deviceData, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));

      // 开发环境和生产环境都调用真实的API
      const response = await api.post('/devices', deviceData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '创建设备失败');
    }
  }
);

// updateDevice 异步 Thunk 函数
// 用于更新设备信息
export const updateDevice = createAsyncThunk(
  'device/updateDevice',
  async ({ id, deviceData }, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));

      // 开发环境和生产环境都调用真实的API
      const response = await api.put(`/devices/${id}`, deviceData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '更新设备失败');
    }
  }
);

// generateQrCode 异步 Thunk 函数
// 用于生成设备二维码
export const generateQrCode = createAsyncThunk(
  'device/generateQrCode',
  async (deviceInfo, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 添加调试日志，检查deviceInfo内容
      console.log('原始deviceInfo:', deviceInfo);
      
      // 确保device_code存在且不为空
      if (!deviceInfo.device_code) {
        throw new Error('设备编号不能为空');
      }

      // 转换字段名为后端期望的驼峰命名法
      const formattedDeviceInfo = {
        deviceName: deviceInfo.device_name || '',
        deviceType: deviceInfo.device_type || '',
        deviceCode: deviceInfo.device_code || '', // 确保deviceCode不为undefined
        productionDate: deviceInfo.production_date || null,
        description: deviceInfo.description || ''
      };
      
      // 输出格式化后的设备信息
      console.log('格式化后的设备信息:', formattedDeviceInfo);

      // 首先创建设备以获取设备ID
      const createResponse = await api.post('/devices', formattedDeviceInfo);
      const deviceId = createResponse.data.id;
      
      // 然后使用设备ID调用生成二维码的API
      const response = await api.post(`/devices/${deviceId}/qr-code`);
      return response.data;
    } catch (error) {
      console.error('生成二维码过程中出错:', error);
      return rejectWithValue(error.response?.data || '生成二维码失败');
    }
  }
);

// deleteDevice 异步 Thunk 函数
// 用于删除设备
export const deleteDevice = createAsyncThunk(
  'device/deleteDevice',
  async (id, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));

      // 开发环境和生产环境都调用真实的API
      await api.delete(`/devices/${id}`);
      return id;
    } catch (error) {
      return rejectWithValue(error.response?.data || '删除设备失败');
    }
  }
);

// 初始状态
// 不使用模拟数据，确保没有数据时显示空表格
const initialState = {
  devices: [], // 初始为空数组
  isLoading: false, // 是否正在加载
  error: null, // 错误信息
  total: 0, // 设备总数
  page: 1, // 当前页码
  pageSize: 10, // 每页条数
  filters: {}, // 过滤条件
  selectedDevices: [] // 选中的设备
};

// 创建 slice
const deviceSlice = createSlice({
  name: 'device',
  initialState,
  reducers: {
    // 设置当前页码
    setPage: (state, action) => {
      state.page = action.payload;
    },
    // 设置每页条数
    setPageSize: (state, action) => {
      state.pageSize = action.payload;
    },
    // 设置过滤条件
    setFilters: (state, action) => {
      state.filters = action.payload;
    },
    // 设置选中的设备
    setSelectedDevices: (state, action) => {
      state.selectedDevices = action.payload;
    },
    // 清除错误信息
    clearError: (state) => {
      state.error = null;
    },
    // 重置设备状态
    resetDevices: () => initialState
  },
  extraReducers: (builder) => {
    // fetchDevices
    builder.addCase(fetchDevices.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    });
    builder.addCase(fetchDevices.fulfilled, (state, action) => {
      state.isLoading = false;
      state.devices = action.payload.devices || [];
      state.total = action.payload.total || 0;
    });
    builder.addCase(fetchDevices.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload || '获取设备列表失败';
      // 出错时使用模拟数据作为兜底，确保页面不空白
      state.devices = mockDevices.slice(0, state.pageSize);
      state.total = mockDevices.length;
    });
    
    // createDevice
    builder.addCase(createDevice.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    });
    builder.addCase(createDevice.fulfilled, (state) => {
      state.isLoading = false;
    });
    builder.addCase(createDevice.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload || '创建设备失败';
    });
    
    // updateDevice
    builder.addCase(updateDevice.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    });
    builder.addCase(updateDevice.fulfilled, (state) => {
      state.isLoading = false;
    });
    builder.addCase(updateDevice.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload || '更新设备失败';
    });
    
    // deleteDevice
    builder.addCase(deleteDevice.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    });
    builder.addCase(deleteDevice.fulfilled, (state) => {
      state.isLoading = false;
    });
    builder.addCase(deleteDevice.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload || '删除设备失败';
    });

    // generateQrCode
    builder.addCase(generateQrCode.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    });
    builder.addCase(generateQrCode.fulfilled, (state) => {
      state.isLoading = false;
    });
    builder.addCase(generateQrCode.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload || '生成二维码失败';
    });
  }
});

// 导出 actions
export const { setPage, setPageSize, setFilters, setSelectedDevices, clearError, resetDevices } = deviceSlice.actions;

// 保留原有的导出方式以保持兼容性


// 导出 reducer
export default deviceSlice.reducer;